import logging
import uuid

from webutils.logging import ContextAdapter

default_logger = logging.getLogger('server.service')


class ManagerProxy:
    def __init__(self, manager_cls):
        self.manager_cls = manager_cls
        self.id = uuid.uuid4().hex

    def __get__(self, instance, owner=None):
        if self.id not in instance._manager_mapping:
            instance._manager_mapping[self.id] = self.manager_cls(instance)
        return instance._manager_mapping[self.id]


class Service:
    BASE_LOGGER = default_logger
    required_context = None

    def __init__(self, connection, log_context=None, logger=None, **kwargs):
        self.connection = connection
        self._manager_mapping = {}
        self.log_context = log_context or self.connection.log_context
        if not logger:
            logger = ContextAdapter(self.BASE_LOGGER, self.log_context)
        self.logger = logger
        for key in self.required_context or []:
            value = kwargs.get(key, None)
            assert value is not None, f'context {key} is expected'
            setattr(self, key, value)


class ServiceMixin:
    def service(self, conn, service_cls, **kwargs):
        kwargs.setdefault('log_context', self.log_context)
        return service_cls(conn, **kwargs)
